package com.hjq.fcloud.ui.factory

import android.app.Activity
import android.content.Intent
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.View
import android.widget.TextView
import com.alibaba.fastjson.JSON
import com.hjq.fcloud.R
import com.hjq.fcloud.http.api.GetSelectCodeApi
import com.hjq.fcloud.model.TreeLimitInfoModel
import com.hjq.fcloud.presenter.SelectPresenter
import com.hjq.fcloud.ui.activity.CommonListQueryActivity
import com.hjq.fcloud.ui.dialog.DateDialog
import com.hjq.fcloud.ui.dialog.MenuDialog
import com.google.gson.internal.LinkedTreeMap
import com.hjq.base.BaseActivity
import com.hjq.base.BaseDialog


interface OnChangeListener {
    fun onValueChange(vararg str: String)
    fun onFindView(vararg itemViews: View)
}

interface OnSelectChangeListener {
    fun onValueChange(str: String, pos: Int, codeStr: String)
    fun onFindView(vararg itemViews: View)
}

/**
 * 通过valueType得到view:
 * ①dateRange  日期 2021-12-21,2021-12-30
 * ②dateTimeRange 时间  2021-12-21 10:00:00,2021-12-30  12:00:00（暂时没用到）
 * ③空就input
 * ④select 对应编码
 * ⑤Tree  - 树形结构（单独一个界面） get_dept_user.php
 * ⑥ 城市选择cascader（暂时没用）
 */
class CommonViewSupport {

    private var mSelectDatas: List<GetSelectCodeApi.DataDTO>? = null

    /**
     * 普通输入框
     */
    fun getInputView(activity: Activity, title: String?, defaultInput: String?, listener: OnChangeListener?): View {
        var itemView: View = activity.layoutInflater.inflate(R.layout.common_list_search_input, null)
        var titleTv: TextView = itemView.findViewById(R.id.titleTv)
        titleTv.setText(title)
        var mSearchEt: TextView = itemView.findViewById(R.id.id_search_et)
        listener?.onFindView(mSearchEt)
        mSearchEt.setText(defaultInput)
        mSearchEt.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }

            override fun afterTextChanged(p0: Editable?) {
                var inputStr = p0.toString().trim()
                listener?.onValueChange(inputStr)
            }
        })
        return itemView
    }

    /**
     * 下拉框
     */
    fun getSelectView(activity: CommonListQueryActivity, title: String?, defaultInput: String?, listener: OnSelectChangeListener?): View {
        var itemView: View = activity.layoutInflater.inflate(R.layout.common_list_search_select, null)
        var titleTv: TextView = itemView.findViewById(R.id.titleTv)
        titleTv.setText(title)
        var mSearchTv: TextView = itemView.findViewById(R.id.id_search_tv)
        listener?.onFindView(mSearchTv)
        mSearchTv.setText(defaultInput)
        mSearchTv.setOnClickListener(View.OnClickListener {
                val datas = SelectPresenter.convertToList(mSelectDatas)
                if(datas.size > 0){
                    // 底部选择框
                    MenuDialog.Builder(activity) // 设置 null 表示不显示取消按钮
                        //.setCancel(getString(R.string.common_cancel))
                        // 设置点击按钮后不关闭对话框
                        //.setAutoDismiss(false)
                        .setList(datas)
                        .setListener(object : MenuDialog.OnListener<String> {
                            override fun onCancel(dialog: BaseDialog?) {

                            }

                            override fun onSelected(dialog: BaseDialog?, position: Int, t: String) {
                                var selectStr = t
                                var codeStr = mSelectDatas?.get(position)?.value.toString()
                                listener?.onValueChange(selectStr, position, codeStr)
                                mSearchTv.setText(selectStr)
                            }
                        })
                        .show()
                }
        })
        return itemView
    }


    fun refershSelectViewData(selectDatas: List<GetSelectCodeApi.DataDTO>) {
        this.mSelectDatas = selectDatas
    }


    /**
     * 时间选择
     */
    fun getSelectDateView(activity: CommonListQueryActivity, defaultStr: String?, defaultInput: String?, listener: OnChangeListener?): View {
        var itemView: View = activity.layoutInflater.inflate(R.layout.common_list_search_select_date, null)
        var mStartTs: TextView = itemView.findViewById(R.id.id_ts_start_tv)
        var mEndTs: TextView = itemView.findViewById(R.id.id_ts_end_tv)
        var realHint = "请选择".plus(defaultStr)
        mStartTs.setHint(realHint)
        mEndTs.setHint(realHint)
        listener?.onFindView(mStartTs)
        listener?.onFindView(mEndTs)

        var chooseStartTs = getStartTs(defaultInput, true)
        var chooseEndTs = getStartTs(defaultInput, false)

        mStartTs.setText(chooseStartTs)
        mEndTs.setText(chooseEndTs)

        mStartTs.setOnClickListener {
            // 日期选择对话框
            DateDialog.Builder(activity)
                    .setTitle(activity.getString(R.string.date_title)) // 确定按钮文本
                    .setConfirm(activity.getString(R.string.common_confirm)) // 设置 null 表示不显示取消按钮
                    .setCancel(activity.getString(R.string.common_cancel)) // 设置日期
                    .setListener(object : DateDialog.OnListener {
                        override fun onSelected(
                            dialog: BaseDialog?,
                            year: Int,
                            month: Int,
                            day: Int
                        ) {
                            chooseStartTs = year.toString() + "-" + month.toString() + "-" + day.toString()
                            mStartTs.setText(chooseStartTs)

                            listener?.onValueChange(getHanderTs(chooseStartTs, chooseEndTs))
                        }

                        override fun onCancel(dialog: BaseDialog?) {
                        }
                    })
                    .show()
        }

        mEndTs.setOnClickListener {
            // 日期选择对话框
            DateDialog.Builder(activity)
                    .setTitle(activity.getString(R.string.date_title)) // 确定按钮文本
                    .setConfirm(activity.getString(R.string.common_confirm)) // 设置 null 表示不显示取消按钮
                    .setCancel(activity.getString(R.string.common_cancel)) // 设置日期
                    .setListener(object : DateDialog.OnListener {
                        override fun onSelected(dialog: BaseDialog?, year: Int, month: Int, day: Int) {
                            chooseEndTs = year.toString() + "-" + month.toString() + "-" + day.toString()
                            mEndTs.setText(chooseEndTs)

                            listener?.onValueChange(getHanderTs(chooseStartTs, chooseEndTs))
                        }

                        override fun onCancel(dialog: BaseDialog?) {
                        }
                    })
                    .show()
        }

        return itemView
    }


    private fun getStartTs(defaultInput: String?, isStartTs: Boolean): String {
        if (!TextUtils.isEmpty(defaultInput) && defaultInput!!.contains(",")) {
            if (isStartTs) {
                return defaultInput!!.split(",")[0]
            } else {
                return defaultInput!!.split(",")[1]
            }
        }
        return ""
    }

    /**
     * 得到时间，用逗号拼接，开始时间和结束时间必须成对
     */
    private fun getHanderTs(chooseStartTs: String, chooseEndTs: String): String {
        if (!TextUtils.isEmpty(chooseStartTs) && !TextUtils.isEmpty(chooseEndTs)) {
            return chooseStartTs + "," + chooseEndTs
        }
        return ""
    }


    /**
     * 下拉框
     */
    fun getTreeView(activity: CommonListQueryActivity, title: String?, defaultInput: String?, selectCode: String?, listener: OnChangeListener?): View {
        var itemView: View = activity.layoutInflater.inflate(R.layout.common_list_tree, null)
        //TODO:先屏蔽，需要在放开
//        var titleTv: TextView = itemView.findViewById(R.id.titleTv)
//        titleTv.setText(title)
//        var mSearchLL: View = itemView.findViewById(R.id.id_tree_ll)
//        var mSearchTv: TextView = itemView.findViewById(R.id.id_tree_tv)
//        listener?.onFindView(mSearchTv)
//        mSearchTv.setText(defaultInput)
//        mSearchLL.setOnClickListener(View.OnClickListener {
//
//            var intent = Intent(activity, ListViewActivity::class.java)
//            intent.putExtra(ListViewActivity.INTENT_SELECT_CODE, selectCode)
//            activity.startActivityForResult(intent, BaseActivity.OnActivityCallback { resultCode: Int, data: Intent? ->
//                if (resultCode == Activity.RESULT_OK) {
//                    var codeStr: String = data!!.extras!!.getString(ListViewActivity.INTENT_SELECT_CODE)!!
//                    var nameStr = data!!.extras!!.getString(ListViewActivity.INTENT_SELECT_NAME)!!
//
//                    mSearchTv.setText(nameStr)
//                    if (listener != null) {
//                        listener.onValueChange(codeStr, nameStr)
//                    }
//                }
//            })
//        })
        return itemView
    }

    /**
     * searchTree
     */
    fun getSearchTreeView(activity: CommonListQueryActivity, defaultStr: String?, defaultInput: String?, treeLimitInfo: String, listener: OnChangeListener?): View {
        var itemView: View = activity.layoutInflater.inflate(R.layout.common_list_search_tree, null)
        //TODO:先屏蔽，需要在放开
//        var titleTv: TextView = itemView.findViewById(R.id.titleTv)
//        titleTv.setText(defaultStr)
//        var mSearchLL: View = itemView.findViewById(R.id.searchTreeLl)
//        var mSearchTv: TextView = itemView.findViewById(R.id.searchTreeTv)
//        listener?.onFindView(mSearchTv)
//        mSearchTv.setText(defaultInput)
//
//        val treeLimitInfoModel: TreeLimitInfoModel = TreeLimitInfoParseUtils.parseTreeLimitInfoModel(treeLimitInfo)
//        var uniqueParam = treeLimitInfoModel.unique_param
//        var showName = treeLimitInfoModel.show_name
//
//        mSearchLL.setOnClickListener(View.OnClickListener {
//            try {
//                val intent = SearchTreeActivity.getCommonLauncherIntent(activity,treeLimitInfo)
//                activity.startActivityForResult(intent) { resultCode, data ->
//                    if (resultCode == Activity.RESULT_OK) {
//                        var selectList = data!!.getStringExtra(SearchTreeActivity.INTENT_RESULT_DATA)
//                        val mSearchTree = JSON.parseArray(selectList, LinkedTreeMap::class.java)
//
//                        //得到展示的对应值
//                        var showNameValue = ""
//                        //得到唯一值
//                        var uniqueParamValue = ""
//                        if(mSearchTree != null && mSearchTree.size > 0){
//                            //这里只取一个，所有判断不为空则取第一个
//                            mSearchTree.get(0).let {dataMap->
//                                showNameValue = dataMap.get(showName).toString()
//                                uniqueParamValue = dataMap.get(uniqueParam).toString()
//                            }
//                        }
//                        mSearchTv.setText(showNameValue)
//                        if (listener != null) {
//                            listener.onValueChange(uniqueParamValue, showNameValue)
//                        }
//                    }
//                }
//            }catch (e:Exception){
//                e.printStackTrace()
//            }
//        })
        return itemView
    }
}